/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: QueneListener
 * Author:   石贵武
 * Date:     2018\3\8 0008 10:33
 * Description: 监听器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.web.async;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 〈一句话功能简述〉<br> 
 * 〈监听器〉
 *
 * @author 石贵武
 * @create 2018\3\8 0008
 * @since 1.0.0
 */
@Component
@Slf4j
public class QueneListener implements ApplicationListener<ContextRefreshedEvent> {


    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        new Thread(()->{

            while (true) {

                if (!StringUtils.isEmpty(mockQueue.getCompleteOrder())) {

                    String orderId = mockQueue.getCompleteOrder();
                    log.info("订单返回结果,orderId={}", orderId);
                    deferredResultHolder.getMap().get(orderId).setResult("place order success");
                    mockQueue.setCompleteOrder(null);
                    log.info("订单返回结束,orderId={}", orderId);
                } else {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}